package com.java.URL_UrlConnection;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 根据URL获取文件大小，并在本地创建相同大小的空文件
 */
public class CreateSameSizeFile {
    public static void main(String[] args) throws IOException {
        String path = "网络编程\\com\\java\\URL_UrlConnection\\files";
        String url = "https://pm.myapp.com/invc/xfspeed/qqpcmgr/download/QQPCDownload1530.exe";

        // 文件大小
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
        httpURLConnection.setRequestMethod("HEAD"); // 设置请求方法
        httpURLConnection.setConnectTimeout(3000); // 设置超时间
        httpURLConnection.connect(); // 连接
        long fileSize = httpURLConnection.getContentLength();

        //文件名
        SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = s.format(new Date()) + url.substring(url.lastIndexOf("."));

        // 创建文件
        RandomAccessFile file = new RandomAccessFile(path + File.separator + fileName, "rw");
        file.setLength(fileSize);
        file.close();
    }
}
